package com.xuhao.android.libsocket.impl.blockio.io;

import android.util.Log;

import com.xuhao.android.libsocket.impl.exceptions.ReadException;
import com.xuhao.android.libsocket.packet.ImConfig;
import com.xuhao.android.libsocket.sdk.connection.abilities.IStateSender;
import com.xuhao.android.libsocket.sdk.connection.interfacies.IAction;
import com.xuhao.android.libsocket.utils.ByteBufferUtils;
import com.xuhao.android.libsocket.utils.Logger;

import org.jim.client.DefaultCoreHandler;
import org.jim.common.base.ImPacket;
import org.jim.common.exception.AioDecodeException;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * Created by xuhao on 2017/5/31.
 */

public class ReaderAbsImpl extends AbsReader {

    private ByteBuffer mRemainingBuf;
    private byte[] buff;

    public ReaderAbsImpl(InputStream inputStream, IStateSender stateSender) {
        super(inputStream, stateSender);
        buff = new byte[ImConfig.PACKT_SIZE];
        mRemainingBuf = ByteBuffer.allocate(ImConfig.PACKT_SIZE);
        mRemainingBuf.position(0);
        mRemainingBuf.limit(0);
    }

    @Override
    public void read() throws RuntimeException {
        execRead();
    }

    private void execRead() {
        try {
            int len = mInputStream.read(buff);
            if (len != -1) {
                mRemainingBuf = ByteBufferUtils.composite(mRemainingBuf, buff, len);
                ImPacket packet;
                int remainingLength = mRemainingBuf.limit() - mRemainingBuf.position();
                while (remainingLength > 0) {
                    //截掉上次的数据
                    mRemainingBuf = ByteBufferUtils.cut(mRemainingBuf);
                    if ((packet = DefaultCoreHandler.decode(mRemainingBuf)) == null) {
                        len = mInputStream.read(buff);
                        mRemainingBuf = ByteBufferUtils.composite(mRemainingBuf, buff, len);
                    } else {
                        mStateSender.sendBroadcast(IAction.ACTION_READ_TCP_COMPLETE, packet);
//                        Log.i(" -- Socket -- ", "Parse : " + new String(packet.getBody(), "utf-8"));
                    }
                    remainingLength = mRemainingBuf.limit() - mRemainingBuf.position();
                }
            }
        } catch (IOException e) {
            Logger.error(e);
            e.printStackTrace();
            throw new ReadException(e);
        } catch (AioDecodeException e) {
            Logger.error(e);
            e.printStackTrace();
        }
    }


}
